// 格式化工具函数

// 格式化价格
export const formatPrice = (price, decimals = 2) => {
  if (typeof price !== 'number') {
    price = parseFloat(price) || 0
  }
  return price.toFixed(decimals)
}

// 格式化日期
export const formatDate = (date, format = 'YYYY-MM-DD') => {
  if (!date) return ''
  
  const d = new Date(date)
  if (isNaN(d.getTime())) return ''

  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  const seconds = String(d.getSeconds()).padStart(2, '0')

  return format
    .replace('YYYY', year)
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hours)
    .replace('mm', minutes)
    .replace('ss', seconds)
}

// 格式化时间（相对时间）
export const formatTimeAgo = (date) => {
  if (!date) return ''
  
  const now = new Date()
  const target = new Date(date)
  const diff = now.getTime() - target.getTime()

  const minute = 60 * 1000
  const hour = 60 * minute
  const day = 24 * hour
  const week = 7 * day
  const month = 30 * day
  const year = 365 * day

  if (diff < minute) {
    return '刚刚'
  } else if (diff < hour) {
    return `${Math.floor(diff / minute)}分钟前`
  } else if (diff < day) {
    return `${Math.floor(diff / hour)}小时前`
  } else if (diff < week) {
    return `${Math.floor(diff / day)}天前`
  } else if (diff < month) {
    return `${Math.floor(diff / week)}周前`
  } else if (diff < year) {
    return `${Math.floor(diff / month)}个月前`
  } else {
    return `${Math.floor(diff / year)}年前`
  }
}

// 格式化手机号
export const formatPhone = (phone) => {
  if (!phone) return ''
  const phoneStr = String(phone)
  if (phoneStr.length === 11) {
    return phoneStr.replace(/(\d{3})(\d{4})(\d{4})/, '$1****$3')
  }
  return phoneStr
}

// 格式化地址
export const formatAddress = (address) => {
  if (!address) return ''
  const { provinceName, cityName, districtName, detail } = address
  return `${provinceName}${cityName}${districtName}${detail}`
}

// 格式化订单号
export const formatOrderNumber = (orderNumber) => {
  if (!orderNumber) return ''
  return orderNumber.replace(/(\d{4})(\d{4})(\d{4})/, '$1 $2 $3')
}

// 格式化文件大小
export const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化数字（添加千分位分隔符）
export const formatNumber = (num) => {
  if (typeof num !== 'number') {
    num = parseFloat(num) || 0
  }
  return num.toLocaleString()
}

// 格式化百分比
export const formatPercent = (value, total, decimals = 1) => {
  if (!total || total === 0) return '0%'
  const percent = (value / total) * 100
  return `${percent.toFixed(decimals)}%`
}

// 格式化距离
export const formatDistance = (distance) => {
  if (typeof distance !== 'number') {
    distance = parseFloat(distance) || 0
  }
  
  if (distance < 1000) {
    return `${Math.round(distance)}m`
  } else {
    return `${(distance / 1000).toFixed(1)}km`
  }
}

// 格式化时长
export const formatDuration = (seconds) => {
  if (typeof seconds !== 'number') {
    seconds = parseInt(seconds) || 0
  }
  
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60
  
  if (hours > 0) {
    return `${hours}:${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')}`
  } else {
    return `${minutes}:${String(secs).padStart(2, '0')}`
  }
}

// 格式化状态文本
export const formatStatus = (status, statusMap) => {
  return statusMap[status] || '未知状态'
}

// 格式化标签
export const formatTags = (tags, separator = ',') => {
  if (!tags || !Array.isArray(tags)) return ''
  return tags.join(separator)
}

// 格式化描述（截取指定长度）
export const formatDescription = (text, maxLength = 100) => {
  if (!text) return ''
  if (text.length <= maxLength) return text
  return text.substring(0, maxLength) + '...'
}

// 格式化评分
export const formatRating = (rating, maxRating = 5) => {
  if (typeof rating !== 'number') {
    rating = parseFloat(rating) || 0
  }
  return `${rating.toFixed(1)}/${maxRating}`
}

// 格式化库存
export const formatStock = (stock) => {
  if (typeof stock !== 'number') {
    stock = parseInt(stock) || 0
  }
  
  if (stock === 0) {
    return '缺货'
  } else if (stock < 10) {
    return `仅剩${stock}件`
  } else {
    return '有库存'
  }
}

// 格式化优惠信息
export const formatDiscount = (originalPrice, currentPrice) => {
  if (!originalPrice || !currentPrice) return ''
  
  const original = parseFloat(originalPrice)
  const current = parseFloat(currentPrice)
  
  if (original <= current) return ''
  
  const discount = ((original - current) / original * 100).toFixed(0)
  return `省${discount}%`
}

export default {
  formatPrice,
  formatDate,
  formatTimeAgo,
  formatPhone,
  formatAddress,
  formatOrderNumber,
  formatFileSize,
  formatNumber,
  formatPercent,
  formatDistance,
  formatDuration,
  formatStatus,
  formatTags,
  formatDescription,
  formatRating,
  formatStock,
  formatDiscount
}
